/**
 * OWASP GoatDroid Project
 * 
 * This file is part of the Open Web Application Security Project (OWASP)
 * GoatDroid project. For details, please see
 * https://www.owasp.org/index.php/Projects/OWASP_GoatDroid_Project
 *
 * Copyright (c) 2011 - The OWASP Foundation
 * 
 * GoatDroid is published by OWASP under the GPLv3 license. You should read and accept the
 * LICENSE before you use, modify, and/or redistribute this software.
 * 
 * @author Jack Mannino, nVisium Security (https://www.nvisiumsecurity.com)
 * @created 2011
 */
package org.owasp.goatdroid.gui;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

public class LessonTreeBuilder {

	private static String LESSON_DIRECTORY;
	private static String slash;

	public LessonTreeBuilder() {

		if (System.getProperty("os.name").toLowerCase().startsWith("windows"))
			slash = File.separator + File.separator;
		else
			slash = File.separator;

		URL url = this.getClass().getProtectionDomain().getCodeSource()
				.getLocation();
		String link = url.toString();
		//If we are running outside of Eclipse
		if (link.endsWith(".jar")) {
			String[] pathSplit = link.split("/");
			String localLink = "";
			for (int count = 1; count < pathSplit.length - 1; count++) 
				localLink += pathSplit[count] + slash;

			link = localLink;
			//To run in Eclipse
		} else
			link = link.replace("file:/", "");
		if (System.getProperty("os.name").toLowerCase().startsWith("windows"))
			link = link.replace("/", slash);
		link = link + "goatdroid_apps";
		if (!System.getProperty("os.name").toLowerCase().startsWith("windows"))
			link = slash + link;
		LESSON_DIRECTORY = link;
		try {
			LESSON_DIRECTORY = URLDecoder.decode(LESSON_DIRECTORY, "UTF-8");
		} catch (UnsupportedEncodingException e) {

		}
	}

	public JTree buildTree() {
		DefaultMutableTreeNode lessonNode = createNodes();
		JTree tree = new JTree(lessonNode);
		return tree;
	}

	public DefaultMutableTreeNode createNodes() {
		// this is the top node of our tree
		DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Apps");
		File lessonRoot = new File(LESSON_DIRECTORY);

		try {
			// first we start with the categories
			for (File lessonCategory : lessonRoot.listFiles()) {
				// we should only look for folders to crawl through
				if (lessonCategory.isDirectory()) {
					DefaultMutableTreeNode lessonCategoryNode;
					String[] splitLessonCategory = lessonCategory.toString()
							.split(slash);
					lessonCategoryNode = new DefaultMutableTreeNode(
							splitLessonCategory[splitLessonCategory.length - 1]);
					// now we drill down to individual lessons
					for (File lesson : lessonCategory.listFiles()) {
						if (lesson.isDirectory()) {
							String[] splitLesson = lesson.toString().split(
									slash);
							DefaultMutableTreeNode lessonNode = new DefaultMutableTreeNode(
									splitLesson[splitLesson.length - 1]);
							// adding a lesson to a category node
							lessonCategoryNode.add(lessonNode);
						}
					}
					// putting the categories into the topmost node
					topNode.add(lessonCategoryNode);
				}
			}
		}

		catch (NullPointerException e) {
			topNode = new DefaultMutableTreeNode("Error Populating Lessons"
					+ "");
		}

		return topNode;

	}

	static public File readFile(String filePath) {

		File xmlFile = new File(filePath);
		return xmlFile;
	}

	static public String getCurrentNodeParent(JTree tree) {
		try {
			String currentPath = tree.getLastSelectedPathComponent().toString();
			Object[] paths = tree.getSelectionPath().getPath();
			if (!currentPath.matches(paths[1].toString()))
				return LESSON_DIRECTORY + slash + paths[1].toString()
						+ File.separator + currentPath;
			else
				return LESSON_DIRECTORY + slash + paths[1].toString();
		}
		/*
		 * This only fires when you re-request the top node easy enough to catch
		 */
		catch (ArrayIndexOutOfBoundsException e) {
			return "";
		}
	}

	static public Boolean isLessonDirectory(String filePath) {
		File file = new File(filePath + slash + "lesson_info.html");
		if (file.exists())
			return true;
		else
			return false;
	}

	static public String createSolutionURL(JTree tree) {

		return "file:" + slash + slash + getCurrentNodeParent(tree) + slash
				+ "solution.html";
	}

	static public String createLessonInfoURL(JTree tree) {

		return "file:" + slash + File.separator + getCurrentNodeParent(tree)
				+ File.separator + "lesson_info.html";
	}
}
